package com.jcompressor.digest;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;

import org.apache.commons.lang.math.NumberUtils;

import com.jcompressor.exceptions.JcompressorException;

public class ChecksumUtils {
	
	public static long createChecksum(final String streamStr) {
		try {
			return ChecksumUtils.createChecksum(new ByteArrayInputStream(streamStr.getBytes("UTF-8")));
		}
		catch (final UnsupportedEncodingException e) {
			throw new JcompressorException(e);
		}
	}
	
	public static long createChecksum(final InputStream stream) {
		try {
			CheckedInputStream checkedStream = null;
			long checksum = NumberUtils.INTEGER_ZERO;
			
			try {
				checkedStream = new CheckedInputStream(stream, new Adler32());
				final byte[] tempBuf = new byte[128];
				while (checkedStream.read(tempBuf) >= NumberUtils.INTEGER_ZERO) {}
				checksum = checkedStream.getChecksum().getValue();
			}
			catch (final IOException e) {
				checksum = NumberUtils.INTEGER_ZERO;
			}
			finally {
				if (checkedStream != null) {
					try {
						checkedStream.close();
					}
					catch (final IOException e) {
						throw new JcompressorException(e);
					}
				}
			}
			
			return checksum;
		}
		catch (final Exception e) {
			throw new JcompressorException(e);
		}
	}
	
	/*
	public static String generateMD5(final LinkedList<InputStream> streams) {
		SequenceInputStreamWrapper stream = null;
		
		try {
			final ListOfFiles files = new ListOfFiles(streams);
			if (files.size() > NumberUtils.INTEGER_ZERO) {
				stream = new SequenceInputStreamWrapper(new ListOfFiles(streams));
				final MessageDigest digester = MessageDigest.getInstance("MD5");
				
				byte[] buffer = new byte[8192];
				int number = stream.read(buffer);
				// int count = 1;
				// int length = 0;
				
				while (number > 0) {
					digester.update(buffer, 0, buffer.length);
					// length = (length + buffer.length);
					// count++;
					
					number = stream.read(buffer);
				}
				
				final BigInteger checksum = new BigInteger(1, digester.digest());
				final String output = checksum.toString(16);
				return output;
			}
			
			return StringUtils.EMPTY;
		}
		catch (IOException e) {
			throw new JcompressorException(e);
		}
		catch (NoSuchAlgorithmException e) {
			throw new JcompressorException(e);
		}
		finally {
			IOUtils.closeQuietly(stream);
		}
	}
	*/
	
}